/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
#include "main.h"
#include "dma.h"
#include "fatfs.h"
#include "sdio.h"
#include "usart.h"
#include "gpio.h"
#include "hd_w25qxx.h"
#include "pd_spi_hd.h"
#include "hd_led.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
HAL_SD_CardInfoTypeDef SDCardInfo;

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
static void printf_sdcard_info(void);

static void download_font_lib(const TCHAR *filename, W25Qxx *w25Qxx, uint32_t addr);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_SDIO_SD_Init();
  MX_USART1_UART_Init();
  MX_FATFS_Init();
    /* USER CODE BEGIN 2 */
    SD_Driver.disk_initialize(0);
    /* USER CODE BEGIN 2 */
    printf_sdcard_info();
    /* USER CODE END 2 */

    GPIO *gpio = GPIOBuilder.build(GPIOB, LL_GPIO_PIN_2);
    LED *led = LEDBuilder.build(gpio);
    led->init(led);

    GPIO *spi1SselGPIO[] = {GPIOBuilder.build(GPIOA, LL_GPIO_PIN_2),   // OLED
                            GPIOBuilder.build(GPIOA, LL_GPIO_PIN_4),   // W25Q64 on chip
                            GPIOBuilder.build(GPIOC, LL_GPIO_PIN_4),}; // W25Q64 external
    GPIO *spi1SclkGPIO = GPIOBuilder.build(GPIOA, LL_GPIO_PIN_5); // Clock, SPIx_SCK
    GPIO *spi1MisoGPIO = GPIOBuilder.build(GPIOA, LL_GPIO_PIN_6); // MOSI,  SPIx_MOSI
    GPIO *spi1MosiGPIO = GPIOBuilder.build(GPIOA, LL_GPIO_PIN_7); // MOSI,  SPIx_MOSI
    SPIGPIO *spi1GPIO = SPIGPIOBuilder.build(spi1SselGPIO, 3, spi1SclkGPIO, spi1MosiGPIO, spi1MisoGPIO);

    SPI *spi1 = (SPI *) SPIHardwareBuilder.build(SPI1, spi1GPIO);
    spi1->init(spi1);

    W25Qxx *w25Qxx3OnChip = W25QxxBuilder.build(spi1, spi1SselGPIO[1]);
    w25Qxx3OnChip->init(w25Qxx3OnChip);


    retSD = f_mount(&SDFatFS, SDPath, 0);
    printf("mount: %d\n", retSD);

    download_font_lib("unicode_24.ftl", w25Qxx3OnChip, 0x0068D000);
    download_font_lib("unicode_16.ftl", w25Qxx3OnChip, 0x005E8000);
    download_font_lib("unicode_12.ftl", w25Qxx3OnChip, 0x0056B000);
    download_font_lib("gbk_24.ftl",     w25Qxx3OnChip, 0x003C4800);
    download_font_lib("gbk_16.ftl",     w25Qxx3OnChip, 0x00309000);
    download_font_lib("gbk_12.ftl",     w25Qxx3OnChip, 0x0027A800);
    download_font_lib("gb2312_24.ftl",  w25Qxx3OnChip, 0x001E9800);
    download_font_lib("gb2312_16.ftl",  w25Qxx3OnChip, 0x001A8800);
    download_font_lib("gb2312_12.ftl",  w25Qxx3OnChip, 0x00176800);

    f_mount(NULL, SDPath, 1);
    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while (1) {
        /* USER CODE END WHILE */
        led->turn(led);
        HAL_Delay(1000);
        /* USER CODE BEGIN 3 */
    }
    /* USER CODE END 3 */
}

/**
 * | W25Q64 address          | charset    | size              |
 * | ----------------------- | ---------- | ----------------- |
 * | 0x007FF000 ~ 0x0068D000 | unicode 24 | 1480k(0x00172000) |
 * | 0x0068D000 ~ 0x005E8000 | unicode 16 |  660k(0x000A5000) |
 * | 0x005E8000 ~ 0x0056B000 | unicode 12 |  500k(0x0007D000) |
 * | 0x0056B000 ~ 0x003C4800 |     gbk 24 | 1690k(0x001A6800) |
 * | 0x003C4800 ~ 0x00309000 |     gbk 16 |  750k(0x000BB800) |
 * | 0x00309000 ~ 0x0027A800 |     gbk 12 |  570k(0x0008E800) |
 * | 0x0027A800 ~ 0x001E9800 |  gb2312 24 |  580k(0x00091000) |
 * | 0x001E9800 ~ 0x001A8800 |  gb2312 16 |  260k(0x00041000) |
 * | 0x001A8800 ~ 0x00176800 |  gb2312 12 |  200k(0x00032000) |
 *
 * @param filename
 * @param w25Qxx
 * @param addr
 */
static void download_font_lib(const TCHAR *filename, W25Qxx *w25Qxx, uint32_t addr) {
    BYTE buf[4096];
    UINT len;

    retSD = f_open(&SDFile, filename, FA_OPEN_EXISTING | FA_READ);

    while (1) {
        retSD = f_read(&SDFile, buf, 4096, &len);
        if (len <= 0) break;

        w25Qxx->write(w25Qxx, addr, buf, len);
        addr += len;
    }

    f_close(&SDFile);

    printf("%s write done\n", filename);
}

static void printf_sdcard_info(void) {
    uint64_t CardCap;        //SD卡容量
    HAL_SD_CardCIDTypeDef SDCard_CID;

    HAL_SD_GetCardCID(&hsd, &SDCard_CID);       // 获取CID
    HAL_SD_GetCardInfo(&hsd, &SDCardInfo);  // 获取SD卡信息
    CardCap = (uint64_t) (SDCardInfo.LogBlockNbr) * (uint64_t) (SDCardInfo.LogBlockSize);    // 计算SD卡容量
    switch (SDCardInfo.CardType) {
        case CARD_SDSC: {
            if (SDCardInfo.CardVersion == CARD_V1_X)
                printf("Card Type:SDSC V1\r\n");
            else if (SDCardInfo.CardVersion == CARD_V2_X)
                printf("Card Type:SDSC V2\r\n");
        }
            break;
        case CARD_SDHC_SDXC:
            printf("Card Type:SDHC\r\n");
            break;
        default:
            break;
    }

    printf("Card ManufacturerID: %d \r\n", SDCard_CID.ManufacturerID);             // 制造商ID
    printf("CardVersion:         %d \r\n", (uint32_t) (SDCardInfo.CardVersion));   // 卡版本号
    printf("Class:               %d \r\n", (uint32_t) (SDCardInfo.Class));         //
    printf("Card RCA(RelCardAdd):%d \r\n", SDCardInfo.RelCardAdd);                 // 卡相对地址
    printf("Card BlockNbr:       %d \r\n", SDCardInfo.BlockNbr);                   // 块数量
    printf("Card BlockSize:      %d \r\n", SDCardInfo.BlockSize);                  // 块大小
    printf("LogBlockNbr:         %d \r\n", (uint32_t) (SDCardInfo.LogBlockNbr));   // 逻辑块数量
    printf("LogBlockSize:        %d \r\n", (uint32_t) (SDCardInfo.LogBlockSize));  // 逻辑块大小
    printf("Card Capacity:       %.2f GB\r\n", 1.0 * CardCap / 1024 / 1024 / 1024);
}


/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  LL_FLASH_SetLatency(LL_FLASH_LATENCY_5);
  while(LL_FLASH_GetLatency()!= LL_FLASH_LATENCY_5)
  {
  }
  LL_PWR_SetRegulVoltageScaling(LL_PWR_REGU_VOLTAGE_SCALE1);
  LL_RCC_HSI_SetCalibTrimming(16);
  LL_RCC_HSI_Enable();

   /* Wait till HSI is ready */
  while(LL_RCC_HSI_IsReady() != 1)
  {

  }
  LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSI, LL_RCC_PLLM_DIV_8, 168, LL_RCC_PLLP_DIV_2);
  LL_RCC_PLL_Enable();

   /* Wait till PLL is ready */
  while(LL_RCC_PLL_IsReady() != 1)
  {

  }
  while (LL_PWR_IsActiveFlag_VOS() == 0)
  {
  }
  LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);
  LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_4);
  LL_RCC_SetAPB2Prescaler(LL_RCC_APB2_DIV_2);
  LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL);

   /* Wait till System clock is ready */
  while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL)
  {

  }
  LL_SetSystemCoreClock(168000000);

   /* Update the time base */
  if (HAL_InitTick (TICK_INT_PRIORITY) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1) {
    }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
